package com.encryptdemo.encrypt.aop;


import com.encryptdemo.encrypt.annotation.EncryptDecrypt;
import com.encryptdemo.encrypt.util.AESUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class EncryptDecryptAdvice implements ResponseBodyAdvice<Object> {

    private final String key = "1234567890123456";
    private final ObjectMapper objectMapper = new ObjectMapper(); // JSON 序列化工具

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 判断是否有 @EncryptDecrypt 注解
        return returnType.getMethodAnnotation(EncryptDecrypt.class) != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 处理加密逻辑
        if (body == null) {
            return null; // 没有返回值时，不处理
        }

        try {
            // 将返回值序列化为 JSON 字符串
            String jsonString = objectMapper.writeValueAsString(body);

            // 对序列化后的 JSON 字符串进行 AES 加密
            return AESUtil.encrypt(jsonString,key);
        } catch (Exception e) {
            // 捕获加密异常，抛出运行时异常，供日志和调试使用
            throw new RuntimeException("Error during encryption in EncryptDecryptAdvice", e);
        }
    }
}
